package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.MarketCouponManager;
import com.fish.anne.model.MarketCoupon;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class MarketCouponAction extends BaseAction implements Preparable {
    private MarketCouponManager marketCouponManager;
    private List marketCoupons;
    private MarketCoupon marketCoupon;
    private Long  couponId;

    public void setMarketCouponManager(MarketCouponManager marketCouponManager) {
        this.marketCouponManager = marketCouponManager;
    }

    public List getMarketCoupons() {
        return marketCoupons;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String marketCouponId = getRequest().getParameter("marketCoupon.couponId");
            if (marketCouponId != null && !marketCouponId.equals("")) {
                marketCoupon = marketCouponManager.get(new Long(marketCouponId));
            }
        }
    }

    public String list() {
        marketCoupons = marketCouponManager.getAll();
        return SUCCESS;
    }

    public void setCouponId(Long  couponId) {
        this. couponId =  couponId;
    }

    public MarketCoupon getMarketCoupon() {
        return marketCoupon;
    }

    public void setMarketCoupon(MarketCoupon marketCoupon) {
        this.marketCoupon = marketCoupon;
    }

    public String delete() {
        marketCouponManager.remove(marketCoupon.getCouponId());
        saveMessage(getText("marketCoupon.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (couponId != null) {
            marketCoupon = marketCouponManager.get(couponId);
        } else {
            marketCoupon = new MarketCoupon();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (marketCoupon.getCouponId() == null);

        marketCouponManager.save(marketCoupon);

        String key = (isNew) ? "marketCoupon.added" : "marketCoupon.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}